<script>
import draggable from 'vuedraggable'
import render from '@/components/render/render'
//组件复制、删除按钮
const components = {
  itemBtns(h, currentItem, index, list, subitem) {
    const { copyItem, deleteItem } = this.$listeners
    return [
      <span class="drawing-item-copy" title="复制" onClick={event => {
        copyItem(currentItem, list); event.stopPropagation()
      }}>
        <i class="el-icon-copy-document" />
      </span>,
      <span class="drawing-item-delete" title="删除" onClick={event => {
        deleteItem(index, list, subitem); event.stopPropagation()
      }}>
        <i class="el-icon-delete" />
      </span>
    ]
  }
}
//列布局、行布局组件渲染
const layouts = {
  colFormItem(h, currentItem, index, list) {
    const { activeItem } = this.$listeners
    const config = currentItem.__config__
    const child = renderChildren.apply(this, arguments)
    let className = this.activeId === config.formId ? 'drawing-item active-from-item' : 'drawing-item'
    if (this.formConf.unFocusedComponentBorder) className += ' unfocus-bordered'
    let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null
    if (config.showLabel === false) labelWidth = '0'
    if(this.formConf.disabled){
      //禁用富文本
      if(config.tag==='tinymce'){
        currentItem.readonly = true
      }
    }
    if(config.tag==='Steps'){
    const slotOptions = currentItem.__slot__.options
      return (
        <el-col span={config.span} class={className}
          nativeOnClick={event => { activeItem(currentItem); event.stopPropagation() }}>
            <render key={config.renderKey} conf={currentItem} onInput={ event => {
              this.$set(config, 'defaultValue', event)
            }} onJumpStep={(idx) => {
                this.jumpStep(currentItem, idx)
            }}>
            </render>
            {child[config.active - 1]}
            {components.itemBtns.apply(this, arguments)}
        </el-col>
      )
    }
    let isShowDesc = ['Subform','TitleLine','el-tabs','Steps','el-collapse'].includes(config.tag);
    return (
      <el-col span={config.span} class={className}
        nativeOnClick={event => { activeItem(currentItem); event.stopPropagation() }}>
        <el-form-item label-width={labelWidth}
          label={config.showLabel ? config.label : ''} required={config.required}>
          {this.formConf.labelDescriptionPosition==='icon' && !isShowDesc &&  <span slot="label">{config.showLabel ? config.label : ''}
            {
              config.descriptionMessage ? <el-tooltip content={config.descriptionMessage} placement="top">
                    <i class="el-icon-question" style={{color:'#cacad3'}}></i>
                    </el-tooltip> : ''
            }
                  </span>}
          <render viewFlag={'formDesign'} key={config.renderKey} conf={currentItem} onInput={ event => {
            this.$set(config, 'defaultValue', event)
          }}>
            {child}
          </render>
          <div style={{color:'#909399'}}>{this.formConf.labelDescriptionPosition==='button' && !isShowDesc && config.descriptionMessage}</div>
        </el-form-item>
        {components.itemBtns.apply(this, arguments)}
      </el-col>
    )
  },
  rowFormItem(h, currentItem, index, list, subitem) {
    const { activeItem } = this.$listeners
    const config = currentItem.__config__
    const className = this.activeId === config.formId
      ? 'drawing-row-item active-from-item'
      : 'drawing-row-item'
    let child = renderChildren.apply(this, arguments)
    if (currentItem.type === 'flex') {
      child = <el-row type={currentItem.type} justify={currentItem.justify} align={currentItem.align}>
              {child}
            </el-row>
    }
    // 选项卡/折叠面板
    if (config.tag === 'el-tabs' || config.tag === 'el-collapse' || config.tag === 'Steps') {
      return (
        <el-col span={config.span}>
          <el-row
            gutter={config.gutter}
            class={className}
            nativeOnClick={(event) => {
              activeItem(currentItem);
              event.stopPropagation();
            }}
          >
            <render child={child} key={config.renderKey} conf={currentItem}></render>
            {components.itemBtns.apply(this, arguments)}
          </el-row>
        </el-col>
      )
    }
    return (
      <el-col span={config.span}>
        <el-row gutter={config.gutter} class={className}
          nativeOnClick={event => { activeItem(currentItem); event.stopPropagation() }}>
          {currentItem.componentName &&
          currentItem.componentName !== "el-row" ? (
            <span class="component-name">{config.componentName}</span>
          ) : null}
          {config.tag === 'el-card' && <div style={{lineHeight: '36px',fontSize: '14px',fontWeight: 600,marginLeft: '15px',marginBottom: '-15px'}}>{config.label}</div>}
          <draggable
            list={config.children || []}
            animation={340}
            group="componentsGroup"
            class="drag-wrapper"
          >
            {child}
          </draggable>
          {
            // 选项卡中的行容器屏蔽右上角复制和删除按钮
            currentItem.componentName === "el-row" &&
            currentItem.itemBtns === false
              ? null
              : components.itemBtns.apply(this, arguments)
          }
        </el-row>
      </el-col>
    )
  },
  raw(h, currentItem, index, list) {
    const config = currentItem.__config__
    const child = renderChildren.apply(this, arguments)
    return <render key={config.renderKey} conf={currentItem} onInput={ event => {
      this.$set(config, 'defaultValue', event)
    }}>
      {child}
    </render>
  }
}
const tableLayouts = {
  colFormItem(h, currentItem, index, list, subitem) {
    const { activeItem } = this.$listeners
    const config = currentItem.__config__
    const child = renderChildren1.apply(this, arguments)
    let className = this.activeId === config.formId ? 'drawing-item active-from-item' : 'drawing-item'
    if (this.formConf.unFocusedComponentBorder) className += ' unfocus-bordered'
    return (
      <div style='width:170px' class={className}
        onClick={event => { activeItem(currentItem); event.stopPropagation() }}>
          <table style='border:1px dashed #ccc;width: 100%'>
            <tr style='height:40px;textAlign:center;line-height: 30px;font-size: 12px'>{config.label}</tr>
            <tr>
               <render key={config.renderKey} conf={currentItem} onInput={ event => {
                this.$set(config, 'defaultValue', event)
                }}>
                {child}
              </render>
            </tr>
          </table>
           {components.itemBtns.apply(this, arguments)}
      </div>
    )
  },
  rowFormItem(h, currentItem, index, list, subitem) {
    const { activeItem } = this.$listeners
    const config = currentItem.__config__
    const option=currentItem.options
    const className = this.activeId === config.formId
      ? 'drawing-row-item active-from-item'
      : 'drawing-row-item'
    let child = renderChildren1.apply(this, arguments)
    const width=(child.length+1)*170+'px'
    const style=`width:${width};display: flex;padding: 10px 0 0 0;min-width:600px`
    if (currentItem.type === 'flex') {
      child = <el-row type={currentItem.type} justify={currentItem.justify} align={currentItem.align}>
              {child}
            </el-row>
    }
    // 画布内表格组件渲染
    if(config.tag==='Subform'){
      let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null
      if (config.showLabel === false) labelWidth = '0'
      return (
        <el-col span={config.span}>
          <el-row gutter={config.gutter} class={className}
            nativeOnClick={event => { activeItem(currentItem); event.stopPropagation() }}>
            {currentItem.componentName &&
            currentItem.componentName !== "el-row" ? (
              <span class="component-name">{config.componentName}</span>
            ) : null}
            <div style='display: flex;justify-content: space-between;align-items: center;margin: 10px 10px 10px 0'>
               <el-form-item label={config.showLabel ? config.label : ''} labelWidth={config.showLabel && labelWidth} required></el-form-item>
              <div>
                {option.filter(item=>item.position==='table').map(item=><el-button size="mini">{item}</el-button>)}
              </div>
            </div>
              {child}
            {
              // 选项卡中的行容器屏蔽右上角复制和删除按钮
              currentItem.componentName === "el-row" &&
              currentItem.itemBtns === false
                ? null
                : components.itemBtns.apply(this, arguments)
            }
          </el-row>
        </el-col>
      )
    }
    const filterStr = ['子表单', '分割线', '标题', '选项卡', '步骤条', '折叠面板', '卡片布局']
    const filterTag = ['Subform', 'TitleLine', 'TitleLine', 'el-tabs', 'Steps', 'el-collapse', 'el-card']
     return (
        <div gutter={config.gutter} class={className} style='overflowX:auto'
          onClick={event => { activeItem(currentItem); event.stopPropagation() }}>
          {currentItem.componentName &&
          currentItem.componentName !== "el-row" ? (
            <span class="component-name">{config.componentName}</span>
          ) : null}
          <draggable
            list={config.children || []}
            animation={340}
            group="componentsGroup"
            style={style}
            class="drag-wrapper"
            ghostClass='ghost'
            onAdd={(e)=>{
                const trimName = e.item.innerText.trim().replaceAll(' ', '');
               if(filterStr.includes(trimName)){
                  this.$message.warning('子表单不支持布局型组件')
                  config.children=config.children.filter(item => !filterTag.includes(item.__config__.tag))
                }
            }}
          >
            {child}
          </draggable>
          {
            // 选项卡中的行容器屏蔽右上角复制和删除按钮
            currentItem.componentName === "el-row" &&
            currentItem.itemBtns === false
              ? null
              : components.itemBtns.apply(this, arguments)
          }
        </div>
     )
  },
  raw(h, currentItem, index, list) {
    const config = currentItem.__config__
    const child = renderChildren.apply(this, arguments)
    return <render key={config.renderKey} conf={currentItem} onInput={ event => {
      this.$set(config, 'defaultValue', event)
    }}>
      {child}
    </render>
  }
}
//渲染子组件
function renderChildren(h, currentItem, index, list) {
  const config = currentItem.__config__
  if (!Array.isArray(config.children)) return null
  return config.children.map((el, i) => {
    const layout =layouts[el.__config__.layout]
    if (layout) {
      return layout.call(this, h, el, i, config.children, currentItem)
    }
    return layoutIsNotFound.call(this)
  })
}
function renderChildren1(h, currentItem, index, list, subitem) {
  const config = currentItem.__config__
  if (!Array.isArray(config.children)) return null
  return config.children.map((el, i) => {
    const layout =tableLayouts[el.__config__.layout]
    if (layout) {
      return layout.call(this, h, el, i, config.children, currentItem)
    }
    return layoutIsNotFound.call(this)
  })
}

function layoutIsNotFound() {
  throw new Error(`没有与${this.currentItem.__config__.layout}匹配的layout`)
}

export default {
  components: {
    render,
    draggable
  },
  props: [
    'currentItem',
    'index',
    'drawingList',
    'activeId',
    'formConf'
  ],
  methods: {
    // 步骤条点击
    jumpStep (currentItem, stepIdx) {
        const curCompIdx = this.drawingList.findIndex(comp => {
            return comp.__vModel__ === currentItem.__vModel__
        })
        this.$emit('jumpStep', curCompIdx, stepIdx)
    }
  },
  render(h) {
    let layout
    if(this.currentItem.__config__.tag==='Subform'){
      layout=tableLayouts[this.currentItem.__config__.layout]
    }else{
      layout=layouts[this.currentItem.__config__.layout]
    }
    if (layout) {
      return layout.call(this, h, this.currentItem, this.index, this.drawingList)
    }
    return layoutIsNotFound.call(this)
  }
}
</script>
<style lang="less" scoped>
/deep/.el-step__title{
    cursor: pointer;
}
</style>
